<template>
  <table>
    <thead>
    <tr>
      <th>知识 ID</th>
      <th>标题</th>
      <th>内容</th>
      <th>发布时间</th>
      <th>图片</th>
      <th>顾问 ID</th>
      <th>操作</th>
    </tr>
    </thead>
    <tbody>
    <tr v-for="(knowledge, index) in knowledgeList" :key="index">
      <td>{{ knowledge.knowledgeId }}</td>
      <td>{{ knowledge.title }}</td>
      <td>{{ knowledge.content }}</td>
      <td>{{ knowledge.publishTime }}</td>
      <td>
        <img :src="getImageUrl(knowledge.image)" alt="知识图片" style="width: 50px; height: 50px;" />
      </td>
      <td>{{ knowledge.consultantId }}</td>
      <td>
        <button class="button" @click="deleteKnowledge(knowledge.knowledgeId)">删除</button>
        <button class="button" @click="showEditDialog(knowledge)">修改</button>
      </td>
    </tr>
    </tbody>
  </table>
  <EditPsychologicalKnowledgeComponent v-if="showEditDialogVisible" :knowledge="editKnowledge" @updateKnowledge="updateKnowledge" @closeDialog="showEditDialogVisible = false"/>
</template>

<script setup>
import { ref, defineProps, defineEmits } from 'vue';
import axios from 'axios';
import EditPsychologicalKnowledgeComponent from "@/components/form/right/sunkaixuan/EditPsychologicalKnowledgeComponent.vue";

// 接收父组件传递的知识列表
const props = defineProps({
  knowledgeList: {
    type: Array,
    required: true
  }
});

const emit = defineEmits(['updateKnowledgeList']);

const deleteKnowledge = async (knowledgeId) => {
  try {
    const response = await axios.delete(`http://127.0.0.1:9090/psychologicalKnowledge/${knowledgeId}`);
    console.log(response.data);
    const newKnowledgeList = props.knowledgeList.filter(knowledge => knowledge.knowledgeId!== knowledgeId);
    emit('updateKnowledgeList', newKnowledgeList);
  } catch (error) {
    console.error('调用接口删除知识时出错:', error);
    alert('删除知识失败，请重试！');
  }
};

const showEditDialogVisible = ref(false);
const editKnowledge = ref({});

const showEditDialog = (knowledge) => {
  editKnowledge.value = {...knowledge };
  showEditDialogVisible.value = true;
};

const updateKnowledge = (updatedKnowledge) => {
  const index = props.knowledgeList.findIndex(knowledge => knowledge.knowledgeId === updatedKnowledge.knowledgeId);
  if (index!== -1) {
    const newKnowledgeList = [...props.knowledgeList];
    newKnowledgeList[index] = updatedKnowledge;
    emit('updateKnowledgeList', newKnowledgeList);
  }
  showEditDialogVisible.value = false;
};

const getImageUrl = (fileName) => {
  return `http://127.0.0.1:9090/file/download/byte/${fileName}`;
};
</script>

<style scoped>
table {
  width: 100%;
  border-collapse: collapse;
}
th, td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}
th {
  background-color: #f2f2f2;
}
.button{
  height:25px;
  font-size: 14px;
  background-color: rgba(64,158,255,0.81);
  width: 100px;
  text-align:  center;
  cursor:pointer;
  border-radius: 10px;
  color: white;
  border: none;
  float: none
}
</style>